package exam.huawei22_3_23;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class LRUCache {
    //哈希表结合双向链表，当使用信息时放到尾部构成最远最多使用，当容量不够时逐出最近的节点
    class DLinkedNode{
        int key;
        int value;
        DLinkedNode pre;
        DLinkedNode next;
        public DLinkedNode(){};
        public DLinkedNode(int _key,int _value){
            key = _key;
            value = _key;
        }
    }
    private int capacity;
    private int size;
    private Map<Integer,DLinkedNode> cache = new HashMap<>();
    private DLinkedNode head;
    private DLinkedNode tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.head = new DLinkedNode();
        this.tail = new DLinkedNode();
        head.next = tail;
        tail.pre = head;
    }

    public int get(int key) {
        DLinkedNode node = cache.get(key);
        if(node==null){
            return -1;
        }
        moveToTail(node);
        return node.value;
    }

    public void put(int key, int value) {
        DLinkedNode node = cache.get(key);
        if(node!=null){
            node.value = value;
            moveToTail(node);
        }else{
            node = new DLinkedNode(key,value);
            cache.put(key,node);
            addToTail(node);
            size++;
            if(size>capacity){
                deletHead();
                size--;
            }
        }
    }

    private void moveToTail(DLinkedNode node){
        //可以先调用删除再调用添加
        node.pre.next = node.next;
        node.next.pre = node.pre;
        tail.pre.next = node;
        node.pre = tail.pre;
        node.next = tail;
        tail.pre = node;
    }
    private void addToTail(DLinkedNode node){
        tail.pre.next = node;
        node.pre = tail.pre;
        tail.pre = node;
        node.next = tail;
    }
    private void deletHead(){
        head.next.next.pre = head;
        head.next = head.next.next;
    }
}

